//
//  CommunityC.m
//  ShopDemo
//
//  Created by 飞扬的青春 on 2018/7/3.
//  Copyright © 2018年 飞扬的青春. All rights reserved.
//

#import "CommunityC.h"
#import "SecondOneCell.h"
#import "SecondDetailCon.h"
#import "MorePingLunController.h"
#import "AddPingLunCon.h"
#import "LoginController.h"
#import "MBProgressHUD+MJ.h"
@interface CommunityC ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate>

@property(nonatomic,strong)UITableView *listTableview;
@property(nonatomic,strong)UIView *headerView;
@property(nonatomic,strong)NSArray *SDCArray;//轮播图数组
@property(nonatomic,strong)NSArray *btnArray;//中间按钮数组
@property(nonatomic,strong)NSMutableArray *contentArray;

@property(nonatomic,assign)NSInteger index;
@property(nonatomic,assign)NSInteger page;



@end

@implementation CommunityC
-(NSMutableArray *)contentArray{
    if (!_contentArray) {
        _contentArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _contentArray;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 1;
    self.page = 0;
    self.contentArray = [NSMutableArray array];
    NSString *strurl = [NSString stringWithFormat:@"/dashop/news/app/list.do?CurrentPage=%ld",self.index];
    [self contentDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:strurl]];
    [self showDataSDCycleMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:@"/dashop/advertise/app/advertisePic.do?ADV_FLAG=WZLB"]];
    [self showDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:@"/dashop/newsort/app/list.do"]];
    
    [self createTableviewMethod];
    [self creatHeaderViewMethod];
    [self addButtionMethod];
  
    self.listTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.page == 10 ) {
            self.index ++;
            NSString *strurl = [NSString stringWithFormat:@"/dashop/news/app/list.do?CurrentPage=%ld",self.index];
            [self contentDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:strurl]];
        }else{
            [self.listTableview.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    self.listTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.index = 1;
        self.page = 0;
        self.contentArray = [NSMutableArray array];
        NSString *strurl = [NSString stringWithFormat:@"/dashop/news/app/list.do?CurrentPage=%ld",self.index];
        [self contentDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:strurl]];
    }];
    
}
//添加按钮
-(void)addButtionMethod{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn addTarget:self action:@selector(addbuttonAction:) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:btn];
    btn.sd_layout
    .bottomSpaceToView(self.view, 80*kJLXWidthScale)
    .rightSpaceToView(self.view, 30*kJLXWidthScale)
    .heightIs(70*kJLXWidthScale)
    .widthIs(70*kJLXWidthScale);
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = btn.width/2;
    [btn setImage:[UIImage imageNamed:@"add_btn.png"] forState:UIControlStateNormal];
}
-(void)addbuttonAction:(UIButton *)sender{
    NSString *username = [UserDefault objectForKey:LogUserName];
    if (username && username.length > 0) {
        AddPingLunCon *addvc = [[AddPingLunCon alloc]init];
        addvc.hidesBottomBarWhenPushed = YES;
        NSMutableArray *muarr = [NSMutableArray array];
        for (NSDictionary *dic in self.btnArray) {
            if ([dic[@"SORT_ALLOW"] integerValue] == 1) {
                [muarr addObject:dic];
            }
        }
        addvc.dataArray = [muarr copy];
        [self.navigationController pushViewController:addvc animated:YES];
    }else{
        LoginController *loginVC = [[LoginController alloc]init];
        loginVC.logBlock = ^(NSDictionary *logdic) {
            
        };
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}
-(void)createTableviewMethod{
    self.listTableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 120*kJLXWidthScale) style:UITableViewStylePlain];
    [self.view addSubview:self.listTableview];
    if (kScreenHeight == 812) {
        self.listTableview.sd_layout
        .bottomSpaceToView(self.view, 34);
    }
    self.listTableview.dataSource = self;
    self.listTableview.delegate = self;
    [self.listTableview registerClass:[SecondOneCell class] forCellReuseIdentifier:@"onecell"];
    //分隔线
    self.listTableview.separatorStyle = UITableViewCellAccessoryNone;
    //去掉尾部多余的空白
    [self.listTableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    
}
-(void)creatHeaderViewMethod{
    self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, (203 + kScreenWidth/5*2)*kJLXWidthScale)];
    self.headerView.backgroundColor = LineBackColor;
    self.listTableview.tableHeaderView = self.headerView;
    
}

-(void)showDataSDCycleMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        self.SDCArray = response;
        NSMutableArray *imagesURLStrings = [NSMutableArray arrayWithCapacity:10];
        for (NSDictionary *dic in self.SDCArray) {
            NSString *url = [MethodClass returnUrlSetStrWSDLURL:dic[@"ADVERTISE_PIC"]];
            [imagesURLStrings addObject:url];
        }
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            
            SDCycleScrollView *cycleScrollView3 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 200*kJLXWidthScale) delegate:self placeholderImage:[UIImage imageNamed:@"secondplace.jpg"]];
            cycleScrollView3.imageURLStringsGroup = imagesURLStrings;
            cycleScrollView3.autoScrollTimeInterval = 2.0;
            [self.headerView addSubview:cycleScrollView3];
        }];
        
    } failBlock:^(NSError *error) {
        
    }];
    
}

-(void)showDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        self.btnArray = response;
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            NSInteger distanceWD = kScreenWidth/5;
            for (int i = 0; i < 5; i ++) {
                NSDictionary *dic = self.btnArray[i];
                MyButton *btn = [[MyButton alloc]initWithFrame:CGRectMake(distanceWD*i, 203*kJLXWidthScale, distanceWD, distanceWD)];
                NSURL *uRL = [NSURL URLWithString:[MethodClass returnUrlSetStrWSDLURL:dic[@"SORT_IMG"]]];
                [btn.imageV sd_setImageWithURL:uRL];
                 btn.titlab.font = [UIFont systemFontOfSize:13*kJLXWidthScale];
                btn.titlab.text = dic[@"SORT_NAME"];
                btn.backgroundColor = [UIColor whiteColor];
                btn.usinfo = dic;
                [btn addTarget:self action:@selector(headerButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [self.headerView addSubview:btn];
            }
            for (int i = 0; i < 5; i ++) {
                MyButton *btn = [[MyButton alloc]initWithFrame:CGRectMake(distanceWD*i, 203*kJLXWidthScale + distanceWD, distanceWD, distanceWD)];
                if (i < 4) {
                    NSDictionary *dic = self.btnArray[i + 5];
                    NSURL *uRL = [NSURL URLWithString:[MethodClass returnUrlSetStrWSDLURL:dic[@"SORT_IMG"]]];
                    [btn.imageV sd_setImageWithURL:uRL];
                    btn.titlab.font = [UIFont systemFontOfSize:13*kJLXWidthScale];
                    btn.titlab.text = dic[@"SORT_NAME"];
                    btn.usinfo = dic;
                    [btn addTarget:self action:@selector(headerButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                    
                }else{
                    btn.titlab.text = @"更多";
                    btn.imageV.image = [UIImage imageNamed:@"More.png"];
                    [btn addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                }
                btn.backgroundColor = [UIColor whiteColor];
                [self.headerView addSubview:btn];
            }
            
            
        }];
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.listTableview reloadData];
        }];
        
    } failBlock:^(NSError *error) {
        
    }];
}


-(void)headerButtonAction:(MyButton *)sender{
    self.contentArray = [NSMutableArray arrayWithCapacity:10];
    NSString *strurl = [NSString stringWithFormat:@"/dashop/news/app/list.do?CurrentPage=1&SORTID=%@",sender.usinfo[@"NEWSORT_ID"]];
    [MBProgressHUD showMessage:@"正在加载"];
    [self contentDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:strurl]];
}

-(void)moreButtonAction:(MyButton *)sender{
    [MBProgressHUD showMessage:@"正在加载"];
    self.contentArray = [NSMutableArray arrayWithCapacity:10];
    [self contentDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:@"/dashop/news/app/list.do?CurrentPage=1"]];
}

//文章列表
-(void)contentDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSArray *arr = response;
        self.page = arr.count;
        for (NSDictionary *dic in arr) {
            [self.contentArray addObject:dic];
        }
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [MBProgressHUD hideHUD];
            [self.listTableview.mj_header endRefreshing];
            [self.listTableview reloadData];
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}




#pragma mark --UITableViewDelegate,UITableViewDataSource--


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.contentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SecondOneCell *cell = [tableView dequeueReusableCellWithIdentifier:@"onecell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = self.contentArray[indexPath.row];
    cell.namelab.text = [NSString stringWithFormat:@"来源：%@",dic[@"STEMFROM"]];
    cell.titlab.text = [NSString stringWithFormat:@"%@",dic[@"TITLE"]];
    cell.contlab.text = [NSString stringWithFormat:@"%@",dic[@"SHORTCONTENT"]];
    cell.datelab.text = [NSString stringWithFormat:@"发布时间：%@",dic[@"CTIME"]];
    [cell.titimageVI sd_setImageWithURL:[NSURL URLWithString:dic[@"IMAGE"]]];
    cell.onebtn.minlab.text = [NSString stringWithFormat:@"%@",dic[@"LIKES"]];
    cell.twobtn.minlab.text = [NSString stringWithFormat:@"%@",dic[@"NEWS_RATES"]];
    [cell.twobtn addTarget:self action:@selector(pinglunButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.onebtn addTarget:self action:@selector(dianzanButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.onebtn.tag = 460 + indexPath.row;
    cell.twobtn.usinfo = dic;
    cell.onebtn.usinfo = dic;
    NSString *dianzanstr = dic[@"LIKEUSERS"];
    NSArray *dianzanArray = [dianzanstr componentsSeparatedByString:@","];
    if ([dianzanArray containsObject:[UserDefault objectForKey:LogUserID]]) {
        cell.onebtn.mineimagevi.image = [UIImage imageNamed:@"zan_sel.png"];
        cell.onebtn.selected = YES;
    }else{
        cell.onebtn.mineimagevi.image = [UIImage imageNamed:@"zan_nom.png"];
         cell.onebtn.selected = NO;
    }
    
    return cell;
   
    
    
}

-(void)dianzanButtonAction:(MineButton *)sender{
    NSString *username = [UserDefault objectForKey:LogUserName];
    if (username && username.length > 0) {
        sender.selected = !sender.selected;
        if (sender.selected) {
            NSString *strurl = [NSString stringWithFormat:@"/dashop/news/app/likes.do?NEWS_ID=%@&USER_ID=%@",sender.usinfo[@"NEWS_ID"],[UserDefault objectForKey:LogUserID]];
            [self dianzanMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:strurl] indexrow:sender.tag - 460];
            NSMutableDictionary *dic = [self.contentArray[sender.tag -460] mutableCopy];
            NSString *dianzanstr = dic[@"LIKEUSERS"];
            NSString *logid = [NSString stringWithFormat:@"%@,%@",dianzanstr,[UserDefault objectForKey:LogUserID]];
            [dic setValue:logid forKey:@"LIKEUSERS"];
            NSInteger liknum = [dic[@"LIKES"] integerValue];
            liknum ++;
            NSString *likes = [NSString stringWithFormat:@"%ld",liknum];
            [dic setValue:likes forKey:@"LIKES"];
            self.contentArray[sender.tag -460] = [dic copy];
            sender.mineimagevi.image = [UIImage imageNamed:@"zan_sel.png"];
        }else{
            NSString *strurl = [NSString stringWithFormat:@"/dashop/news/app/likes.do?NEWS_ID=%@&USER_ID=%@",sender.usinfo[@"NEWS_ID"],[UserDefault objectForKey:LogUserID]];
            [self dianzanMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:strurl] indexrow:sender.tag - 460];
            NSMutableDictionary *dic = [self.contentArray[sender.tag -460] mutableCopy];
            NSString *dianzanstr = dic[@"LIKEUSERS"];
            NSString *idstr = [dianzanstr stringByReplacingOccurrencesOfString:[UserDefault objectForKey:LogUserID] withString:@""];
            NSString *useridstr;
            if ([idstr containsString:@",,"]) {
               useridstr = [idstr stringByReplacingOccurrencesOfString:@",," withString:@","];
            }else if ([idstr hasPrefix:@","]){
                useridstr = [idstr substringFromIndex:1];
            }else if ([idstr hasSuffix:@","]){
                useridstr = [idstr substringToIndex:idstr.length -1];
            }
            [dic setValue:useridstr forKey:@"LIKEUSERS"];
            NSInteger liknum = [dic[@"LIKES"] integerValue];
            if (liknum > 0) {
                liknum --;
            }
            NSString *likes = [NSString stringWithFormat:@"%ld",liknum];
            [dic setValue:likes forKey:@"LIKES"];
            self.contentArray[sender.tag -460] = [dic copy];
            sender.mineimagevi.image = [UIImage imageNamed:@"zan_nom.png"];
        }
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:sender.tag - 460 inSection:0];
        [self.listTableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }else{
        LoginController *loginVC = [[LoginController alloc]init];
        loginVC.logBlock = ^(NSDictionary *logdic) {
            
        };
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
    
}

-(void)dianzanMethodWithUrl:(NSString *)url indexrow:(NSInteger)row{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSDictionary *dic = response;
        if ([dic[@"RESULT"] integerValue] == 1 || [dic[@"RESULT"] integerValue] == -1) {
//            NSString *urlstr = [NSString stringWithFormat:@"/dashop/news/app/list.do?CurrentPage=%ld",self.index];
//            [self contentDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:urlstr] indexrow:row];
        }
    } failBlock:^(NSError *error) {
        
    }];
}
//点赞刷新
-(void)contentDataMethodWithUrl:(NSString *)url indexrow:(NSInteger )row{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSArray *arr = response;
        self.page = arr.count;
        for (NSDictionary *dic in arr) {
            [self.contentArray addObject:dic];
        }
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            if (self.contentArray.count > 0) {
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:row inSection:0];
                [self.listTableview reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}


-(void)pinglunButtonAction:(MineButton *)sender{
    NSString *username = [UserDefault objectForKey:LogUserName];
    if (username && username.length > 0) {
        MorePingLunController *mrvc = [[MorePingLunController alloc]init];
        mrvc.condic = sender.usinfo;
        mrvc.navigationItem.title = @"社区评论";
        mrvc.hidesBottomBarWhenPushed = YES;
        NSString *strurl = [NSString stringWithFormat:@"/dashop/newsrate/app/list.do?NEWS_ID=%@&CurrentPage=1&NEWSRATE_PARENTID=0",sender.usinfo[@"NEWS_ID"]];
        mrvc.urlstr = strurl;
        [self.navigationController pushViewController:mrvc animated:YES];
    }else{
        LoginController *loginVC = [[LoginController alloc]init];
        loginVC.logBlock = ^(NSDictionary *logdic) {
            
        };
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
   
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 205*kJLXWidthScale;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = self.contentArray[indexPath.row];
    SecondDetailCon *dvc = [[SecondDetailCon alloc]init];
    dvc.detailDic = dic;
    dvc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:dvc animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
